package com.jushu.storbox.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.CopyrightActivity;
import com.jushu.storbox.FolderBrowserActivity;
import com.jushu.storbox.InviteFriendActivity;
import com.jushu.storbox.LoackaActivity;
import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.SetLoackActivity;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ShareDriveMainFragmentActivity;
import com.jushu.storbox.actions.LogoutAction;
import com.jushu.storbox.actions.SettingAction;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.service.FileHelper;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.viewImpl.SlipButton;
import com.jushu.storbox.view.viewImpl.SlipButton.OnChangedListener;
import com.huawei.sharedrive.sdk.android.common.Constants;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.ClientInfoResponseV2;

import java.util.Map;
import java.util.Set;

public class SettingFragment extends BaseFragment {
	private View viewLayoutInflater;

	private Activity activity;

	private SlipButton downloadHint;
	
	private SlipButton autoLogin;

	private View clear_btn;
	
	private View cache_folder_btn;

	private Button unregister;

	private ProgressDialog myDialog;

	/** setting back layout */
	private View setting_back_ll;

	/** cloud drive service */
	private ICloudDriveService shareDriveService;

	private TextView sdcardsize_tv;

	private TextView version_tv;
	
	private TextView setting_cachepath_label;

	private RelativeLayout layout_version;

	private RelativeLayout layout_invite_friend;

	private RelativeLayout layout_copyright;

	private TextView tv_has_new_version;

	/** log TAG */
	private String TAG = "SettingActivity";

	private final static int MDMSIZE = 1;

	private boolean isShowToast = true;

	private TextView mShowUserTextView;

	private View layoutChecking, reviseLock;

	private View security_lock_line_view;

	private ClientExceptionRelateHandler upgradeHandler;

	private SlipButton mSlipBtnSafetyLock;

	private Handler activityHandler;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		this.activity = (ShareDriveMainFragmentActivity) activity;
		setBack(false);

		if (null == getObj()) {
			// System.exit(1);
			PublicTools.restartApp(activity);
		} else {
			Map<String, Object> mp = (Map<String, Object>) getObj();

			if (null != mp.get("activityhandler")) {
				activityHandler = (Handler) mp.get("activityhandler");
			} else {
				PublicTools.restartApp(activity);
			}
			if (null != mp.get("service")) {
				shareDriveService = (ICloudDriveService) mp.get("service");
			} else {
				PublicTools.restartApp(activity);
			}
		}
		super.onAttach(activity);
	}

	public String getAvaiableSdCardSize() {
		return FileHelper.formatFileSize(FileHelper.getUsingSDCardSize(
				activity, DirectoryUtil.getCurrentCachePath(activity)));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		viewLayoutInflater = inflater.inflate(R.layout.activity_setting, null);
		findById();
		initDate();
		initListenser();
		initHandler();
		setBack(true);
		return viewLayoutInflater;

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		if (null != shareDriveService) {
			shareDriveService.getCloudDriveCache(settingHandler);
		}
		SharedPreferences settings = activity.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		version_tv.setText(activity
				.getString(R.string.setting_app_version_text)
				+ PublicTools.getVersionName(activity));

		boolean isUpgradeState = settings.getBoolean(
				Constant.CLOUD_UPGRADE_STATE, false);
		if (isUpgradeState) {
			tv_has_new_version.setVisibility(TextView.VISIBLE);
		} else {
			tv_has_new_version.setVisibility(TextView.GONE);
		}
		mSlipBtnSafetyLock.setCheck(settings.getBoolean(
				ClientConfig.AUTO_SAFETY_LOCK, false));
		if (settings.getBoolean(ClientConfig.AUTO_SAFETY_LOCK, false)) {
			reviseLock.setVisibility(View.VISIBLE);
			security_lock_line_view.setVisibility(View.VISIBLE);
		} else {
			reviseLock.setVisibility(View.GONE);
			security_lock_line_view.setVisibility(View.GONE);
		}
		super.onResume();
	}

	private void initHandler() {
		upgradeHandler = new ClientExceptionRelateHandler(){
			
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageCode.VERSION_INFO_SUCCESS:
					//compare version, if need upgrade,then suggest user to upgrade
					ClientInfoResponseV2 versionInfo = (ClientInfoResponseV2)msg.obj;
					shareDriveService.upgradeCloudDrive(null,versionInfo,true);
				default:
					super.handleMessage(msg);
				}
			}

			@Override
			public Context getContext() {
				return getActivity();
			}
		};

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		LogUtil.i(TAG, "onDestroy()");
		ActivityTaskManager.getInstance().removeActivity(TAG);
		super.onDestroy();
	}

	/**
	 * SettingActivity init onclick listenser
	 */
	private void initListenser() {
		downloadHint.SetOnChangedListener(downloadHintListenser);
//		autoSynchronization.SetOnChangedListener(autoSyncListenser);
//		autoSync_wifi.SetOnChangedListener(autoSync_wifiListenser);
		autoLogin.SetOnChangedListener(autoLoginListenser);
		clear_btn.setOnClickListener(clearListenser);
		cache_folder_btn.setOnClickListener(cacheFolderListenser);
//		reviseLock = viewLayoutInflater.findViewById(R.id.revise_Lock_layout);
		mShowUserTextView.setOnClickListener(flowQueryListenser);
		unregister.setOnClickListener(unregisterListenser);
		setting_back_ll.setOnClickListener(backListenser);
		layout_version.setOnClickListener(checkUpgradeListenser);
		layout_invite_friend.setOnClickListener(inviteFriendListener);
		layout_copyright.setOnClickListener(copyrightListener);
		mSlipBtnSafetyLock.SetOnChangedListener(autoSafetyLockListener);
	}

	/**
	 * SettingActivity init data
	 */
	@SuppressLint("NewApi")
	private void initDate() {
		// bindService
		SharedPreferences settings = activity.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		autoLogin.setCheck(settings.getBoolean(ClientConfig.AUTOLOGIN_SETTING,
				true));

		downloadHint.setCheck(PublicTools.getDownloadRemind(activity));
//		albumBackupBtn.setCheck(PublicTools.getAlbumBackup(activity));
		mShowUserTextView.setText(PublicTools.getClientUserName(activity));
	}

	/**
	 * SettingActivity init find view by id
	 */
	public void findById() {
		downloadHint = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
				.findViewById(R.id.downloadHint_sb);
//		albumBackupBtn = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
//				.findViewById(R.id.cameraAutoBackupId);
//		autoSynchronization = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
//				.findViewById(R.id.autoSynchronization_sb);
//		autoSync_wifi = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
//				.findViewById(R.id.autoSynchronization_wifi_sb);
		autoLogin = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
				.findViewById(R.id.autoLogin_sb);
//		mSlipBtnSafetyLock = (com.jushu.storbox.view.viewImpl.SlipButton) viewLayoutInflater
//				.findViewById(R.id.slipbtn_security_lock);
//		setting_back_ll = viewLayoutInflater.findViewById(R.id.setting_back_mi);
		clear_btn = viewLayoutInflater.findViewById(R.id.clear_btn);
		cache_folder_btn = viewLayoutInflater.findViewById(R.id.cache_folder_btn);
		unregister = (Button) viewLayoutInflater
				.findViewById(R.id.unregister_btn);
		sdcardsize_tv = (TextView) viewLayoutInflater
				.findViewById(R.id.sdcardsize_tv);
		setting_cachepath_label = (TextView) viewLayoutInflater
				.findViewById(R.id.setting_cachepath_label);
		setting_cachepath_label.setText(DirectoryUtil.getCurrentCachePath(activity));
		version_tv = (TextView) viewLayoutInflater
				.findViewById(R.id.version_tv);
		layoutChecking = viewLayoutInflater.findViewById(R.id.layout_checking);
		layout_version = (RelativeLayout) viewLayoutInflater
				.findViewById(R.id.layout_version);
		layout_invite_friend = (RelativeLayout) viewLayoutInflater
				.findViewById(R.id.layout_invite_friend);
		layout_copyright = (RelativeLayout) viewLayoutInflater
				.findViewById(R.id.layout_copyright);
		tv_has_new_version = (TextView) viewLayoutInflater
				.findViewById(R.id.flag_has_new_version);
		mShowUserTextView = (TextView) viewLayoutInflater
				.findViewById(R.id.tv_show_user);
		security_lock_line_view = viewLayoutInflater
				.findViewById(R.id.security_lock_line_view);
	}

	/**
	 * SettingActivity logout Listener
	 */
	private OnClickListener backListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {

			activity.finish();

		}
	};

	/**
	 * SettingActivity download toast hint Listener
	 */
	private OnChangedListener downloadHintListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {
			PublicTools.setDownloadRemind(activity, CheckState);
			// Toast.makeText(SettingActivity.this, "" + CheckState,
			// 200).show();
		}
	};

	private OnChangedListener albumBakupListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean checkState) {
			PublicTools.setAlbumBackup(activity, checkState);
			if(checkState){
				((ShareDriveMainFragmentActivity)activity).startAlbumBackup();
			}else{
				((ShareDriveMainFragmentActivity)activity).stopAlbumBackup();
			}
			// Toast.makeText(SettingActivity.this, "" + CheckState,
			// 200).show();
		}
	};

	/**
	 * SettingActivity invite friend Listener
	 */

	private OnClickListener inviteFriendListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(),
					InviteFriendActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	};

	/**
	 * SettingActivity copyright Listener
	 */

	private OnClickListener copyrightListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), CopyrightActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	};

	/**
	 * SettingActivity download toast hint Listener
	 */
	private OnClickListener checkUpgradeListenser = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!ShareDriveApplication.getInstance()
					.getWifiController().getNetworkState()) {
				Toast.makeText(
						activity,
						activity.getString(R.string.clouddrive_mode_without_internet),
						Toast.LENGTH_SHORT).show();
				return;
			}

			// TODO Auto-generated method stub
			SharedPreferences settings = activity.getSharedPreferences(
					ClientConfig.settings, Context.MODE_APPEND);
			// boolean isUpgradeState = settings.getBoolean(
			// Constant.CLOUD_UPGRADE_STATE, true);
			// if (isUpgradeState) {
			// tv_has_new_version.setVisibility(TextView.VISIBLE);
			if (null != shareDriveService) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						new SettingAction().getVersionInfo(activity, upgradeHandler);
//						Message msg = new Message();
//						msg.what = MessageCode.VERSION_INFO_SUCCESS;
//						msg.obj = clientInfo;
//						upgradeHandler.sendMessage(msg);
					}

				}).start();
			}
		}
	};

	private OnChangedListener autoSafetyLockListener = new OnChangedListener() {

		@Override
		public void OnChanged(boolean CheckState) {
			if (CheckState) {
				Intent intent = new Intent(getActivity(),
						SetLoackActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// reviseLock.setVisibility(View.VISIBLE);
				reviseLock.setOnClickListener(new ReviseLockListener());
				getActivity().startActivity(intent);
			} else {
				Intent intent = new Intent(getActivity(), LoackaActivity.class);
				;
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle bundle = new Bundle();
				bundle.putBoolean("iscloseLoack", true);
				intent.putExtras(bundle);
				getActivity().startActivity(intent);
				// reviseLock.setVisibility(View.GONE);
			}

		}
	};

	private class ReviseLockListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {

		}
	}

	/**
	 * SettingActivity auto sync Listener
	 */
	private OnChangedListener autoSyncListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {

			// Toast.makeText(SettingActivity.this, "" + CheckState,
			// 200).show();
		}
	};

	/**
	 * SettingActivity auto wifi sync Listener
	 */
	private OnChangedListener autoSync_wifiListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {

			// Toast.makeText(SettingActivity.this, "" + CheckState,
			// 200).show();
		}
	};

	/**
	 * SettingActivity auto wifi login Listener
	 */
	private OnChangedListener autoLoginListenser = new OnChangedListener() {
		@Override
		public void OnChanged(boolean CheckState) {
			SharedPreferences settings = activity.getSharedPreferences(
					ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			if (CheckState) {
				editor.putBoolean(ClientConfig.AUTOLOGIN, CheckState);
				editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			} else {
				editor.putBoolean(ClientConfig.AUTOLOGIN, CheckState);
				editor.putBoolean(ClientConfig.AUTOLOGIN_SETTING, CheckState);
			}
			editor.commit();

			// Toast.makeText(SettingActivity.this, "" + CheckState,
			// 200).show();
		}
	};

	/**
	 * SettingActivity clear cloud drive all data cache Listener
	 */
	private OnClickListener clearListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			final ClouddriveDialog delete = new ClouddriveDialog(activity,
					R.style.dialog_upload, R.layout.dialog_filedelete);
			View conventView = delete.getConventView();
			Button dialog_cancal = (Button) conventView
					.findViewById(R.id.dialog_add_file_cancal_bt);
			Button dialog_OK = (Button) conventView
					.findViewById(R.id.dialog_add_file_ok_bt);

			TextView dialog_prompt_tv = (TextView) conventView
					.findViewById(R.id.dialog_prompt_tv);

			Set<DownloadTask> downloadTasks = DownloadTaskManager
					.getAllTaskes();
			if (downloadTasks != null && downloadTasks.size() > 0) {
				dialog_prompt_tv.setText(activity
						.getString(R.string.setting_clear_downloading));
			} else {
				dialog_prompt_tv
						.setText(activity
								.getString(R.string.setting_activity_quest_comfirm_clear_cache));
			}
			dialog_cancal.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					delete.dismiss();
				}
			});

			dialog_OK.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					delete.dismiss();
					if (null != shareDriveService) {
						activity.setResult(3);
						shareDriveService.clearCloudDriveCache(settingHandler);
					}
				}
			});
			delete.show();
		}
	};

	private OnClickListener cacheFolderListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(activity, FolderBrowserActivity.class);
			startActivityForResult(intent, 5);
		}
	};

	/**
	 * SettingActivity clear cloud drive all data cache Listener
	 */
	private OnClickListener flowQueryListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			LogUtil.i(TAG, "flowQuery");
			PublicTools.FlowFileCount(activity, activity.getPackageName());
		}
	};

	/**
	 * SettingActivity layout out Listener
	 */
	private OnClickListener unregisterListenser = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			final ClouddriveDialog unregisterDialog = new ClouddriveDialog(
					activity, R.style.dialog_upload, R.layout.dialog_logout_new);
			// unregisterDialog.setCanceledOnTouchOutside(true);
			// unregisterDialog.setWidth(LayoutParams.WRAP_CONTENT);
			// unregisterDialog.setHeigth(LayoutParams.MATCH_PARENT);
			unregisterDialog.show();
			View conventView = unregisterDialog.getConventView();
			Button confirm_btn = (Button) conventView
					.findViewById(R.id.confirm_btn);
			Button cancle_btn = (Button) conventView
					.findViewById(R.id.cancle_btn);
			confirm_btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					myDialog = new ProgressDialog(activity);
					myDialog.setMessage(activity
							.getString(R.string.setting_activity_logouting));
					myDialog.show();
					myDialog.setCanceledOnTouchOutside(false);
					unregisterDialog.dismiss();
					new Thread(new Runnable() {
						@Override
						public void run() {
							String res = "";
							if (shareDriveService != null) {
								Message msg = new Message();
								try {
									res = shareDriveService.logout();
									msg.what = 0;
									LogUtil.e(TAG, "loginout_res:" + res);
								} catch (ClientException e) {
									// TODO Auto-generated catch block
									msg.what = 10;
									LogUtil.e(TAG,
											"statueCode:" + e.getStatusCode());
									e.printStackTrace();
								}
								settingHandler.sendMessageDelayed(msg, 1500);
							}
						}
					}).start();
					if (shareDriveService != null) {
						shareDriveService.destoryMusicplayer();
					}
				}
			});
			cancle_btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					unregisterDialog.dismiss();
				}
			});

		}
	};

	/**
	 * SettingActivity settingHandler
	 */
	private Handler settingHandler = new Handler() {
		@SuppressLint("NewApi")
		public void handleMessage(Message msg) {
			SharedPreferences settings = activity.getSharedPreferences(
					ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			switch (msg.what) {
			case 0:
				myDialog.cancel();
				((ShareDriveMainFragmentActivity)activity).stopAlbumBackup();
				new LogoutAction(activity).logout(activity);
				// shareDriveService.clearCloudDriveCache(settingHandler);//
				isShowToast = false;
				// activity.finish();
				break;
			case 10:
				editor.putString(ClientConfig.LOGINPASSWORD, "");
				editor.putBoolean(ClientConfig.AUTOLOGIN, false);
				editor.putString(ClientConfig.USERNAME, "");
				editor.putBoolean(ClientConfig.NOT_NEED_NOTIFY, false);//
				editor.putString(ClientConfig.UAM_ADDRESS, "");
				editor.putString(ClientConfig.UFM_ADDRESS, "");
				editor.commit();
				Constants.UAM_ADDRESS = "";
				Constants.UFM_ADDRESS = "";
				myDialog.cancel();
				Intent intents = new Intent();
				intents.setClass(activity, LoginActivity.class);
				ActivityTaskManager.getInstance().closeAllActivity();
				startActivity(intents);
				isShowToast = false;
				activity.finish();
				break;
			case MDMSIZE:
				String cloudDriveSize = (String) msg.obj;
				sdcardsize_tv
						.setText(getString(R.string.setting_space_downloaded_lable)
								+ cloudDriveSize
								+ ","
								+ getString(R.string.setting_space_available_lable)
								+ getAvaiableSdCardSize());
				if ("0B".equals(cloudDriveSize) && clear_btn.isEnabled()) {
					clear_btn.setEnabled(false);
				}
				if (!"0B".equals(cloudDriveSize) && !clear_btn.isEnabled()) {
					clear_btn.setEnabled(true);
				}
				// calculateStoredSize();
				break;
			case 2:
				if (isShowToast) {
					Message activityMsg = new Message();
					activityMsg.what = 11;
					activityHandler.sendMessage(activityMsg);

					Toast.makeText(activity,
							activity.getString(R.string.setting_clear_ok), Toast.LENGTH_SHORT)
							.show();
					sdcardsize_tv
							.setText(activity
									.getString(R.string.setting_space_downloaded_lable)
									+ "0B"
									+ ","
									+ activity
											.getString(R.string.setting_space_available_lable)
									+ getAvaiableSdCardSize());
					clear_btn.setEnabled(false);
				} else {
					isShowToast = true;
				}
				break;
			case 3:
				tv_has_new_version.setVisibility(TextView.GONE);
				Toast.makeText(activity,
						activity.getString(R.string.no_need_update), Toast.LENGTH_SHORT)
						.show();
				break;
			case 4:

				break;

			default:
				break;
			}
		};
	};

	@Override
	public void refreshListFromServer() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDataLoaded() {
		// TODO Auto-generated method stub
		if (null != activityHandler) {
			Message dissMissMsg = new Message();
			dissMissMsg.what = 12;
			activityHandler.sendMessageDelayed(dissMissMsg, 100);
		}
	}

	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (resultCode)
        {
            case MessageCode.RESULT_CODE_CACHE_FOLDER:
            	String mCurrentDir = data.getBundleExtra("result").getString("mCurrentDir");
            	setting_cachepath_label.setText(mCurrentDir);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        
    }
}
